package pers.kui.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import pers.kui.mall.common.Constant;
import pers.kui.mall.exception.ExceptionEnum;
import pers.kui.mall.exception.MallException;
import pers.kui.mall.model.dao.ProductMapper;
import pers.kui.mall.model.pojo.Product;
import pers.kui.mall.model.request.AddProductReq;
import pers.kui.mall.model.request.ProductListReq;
import pers.kui.mall.query.ProductListQuery;
import pers.kui.mall.service.CategoryService;
import pers.kui.mall.service.ProductService;
import pers.kui.mall.vo.CategoryVO;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: ldk
 * 描述: 商品服务实现类
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    ProductMapper productMapper;

    @Autowired
    CategoryService categoryService;

    @Override
    public void add(AddProductReq addProductReq) {
        //创建Product实例
        Product product = new Product();
        //2.将新增的product复制到pojo中product类中，对数据进行一次覆盖
        BeanUtils.copyProperties(addProductReq, product);
        //3.通过查询数据库是否有重名的商品，有就添加失败
        Product productOld = productMapper.selectByName(addProductReq.getName());
        if (productOld != null) {
            throw new MallException(ExceptionEnum.NAME_EXISTED);
        }
        //4.进行插入数据操作并判断是否有效插入
        int count = productMapper.insertSelective(product);
        if (count == 0) {
            throw new MallException(ExceptionEnum.CREATE_FAILED);
        }
    }
    @Override
    //更新商品
    public void update(Product updateProduct){
        Product productOld = productMapper.selectByName(updateProduct.getName());
        //同名且不同id，不能修改
        if (productOld != null && !productOld.getId().equals(updateProduct.getId())) {
            throw new MallException(ExceptionEnum.NAME_EXISTED);
        }
        int count = productMapper.updateByPrimaryKeySelective(updateProduct);
        if (count == 0){
            throw new MallException(ExceptionEnum.UPDATE_FAILED);
        }

    }

    @Override
    //删除商品
    public void delete(Integer id){
        //查询删除商品的id主键是否存在
        Product productOld = productMapper.selectByPrimaryKey(id);
        if (productOld == null ) {
            throw new MallException(ExceptionEnum.DELETE_FAILED);
        }
        int count = productMapper.deleteByPrimaryKey(id);
        if (count == 0){
            throw new MallException(ExceptionEnum.DELETE_FAILED);
        }
    }

    @Override
    //批量上下架商品
    public void batchUpdateSellStatus(Integer[] ids, Integer sellStatus) {
        productMapper.batchUpdateSellStatus(ids, sellStatus);
    }

    @Override
    //商品列表
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<Product> products = productMapper.selectListForAdmin();
        PageInfo<Product> pageInfo = new PageInfo<>(products);
        return pageInfo;
    }

    @Override
    //商品详情
    public Product detail(Integer id) {
        Product product = productMapper.selectByPrimaryKey(id);
        return product;
    }

    @Override
    public PageInfo list(ProductListReq productListReq) {
        //构建Query对象
        ProductListQuery productListQuery = new ProductListQuery();
        //搜索处理
        if (!StringUtils.isEmpty(productListReq.getKeyword())) {
            String keyword = new StringBuilder().append("%").append(productListReq.getKeyword()).append("%").toString();
            productListQuery.setKeyword(keyword);
        }
        //目录处理，如果查某个目录下的商品，不仅需要查出该目录下的，还需要把所有子目录的所有商品查出来，所以要拿到一个目录id的List
        if (productListReq.getCategoryId() != null) {
            List<CategoryVO> categoryVOList = categoryService.listCategoryForCustomer(productListReq.getCategoryId());
            ArrayList<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(productListReq.getCategoryId());
            getCategoryIds(categoryVOList, categoryIds);
            productListQuery.setCategoryIds(categoryIds);
        }
        //排序处理
        String orderBy = productListReq.getOrderBy();
        if (Constant.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize(),orderBy);
        }else{
            PageHelper.startPage(productListReq.getPageNum(), productListReq.getPageSize());
        }

        List<Product> productsList= productMapper.selectList(productListQuery);
        PageInfo<Product> pageInfo = new PageInfo<>(productsList);
        return pageInfo;
    }
    private void getCategoryIds(List<CategoryVO> categoryVOList, ArrayList<Integer> categoryIds){
        for (int i = 0; i < categoryVOList.size(); i++) {
            CategoryVO categoryVO =  categoryVOList.get(i);
            if (categoryVO != null) {
                categoryIds.add(categoryVO.getId());
                getCategoryIds(categoryVO.getChildCategory(), categoryIds);
            }
        }
    }
}
